<?php
/**
 * Created by PhpStorm.
 * User: 图图
 * Date: 2021-5-11
 * Time: 9:11
 */

namespace app\manage\admin;
use app\admin\controller\Admin;
use app\common\builder\ZBuilder;
use app\common\model\Goods as Goods_Model;
use app\common\model\Project as Project_Model;
use think\Db;
use app\common\model\Activity as Activity_Model;
use app\common\model\Project;
use app\common\model\ActivityItem;
use app\common\model\ActivityItemViper;
use app\common\model\ViperType;
/**
 * 设置活动
 * Class Combine
 * @package app\manage\admin
 */
class Activity extends Admin
{

    /**
     * 活动列表
     * @return mixed
     * @throws \think\Exception
     */
    public function index(){
        // 读取数据
        $map = $this->getMap();
        // 排序
        $order = $this->getOrder();
        // 数据列表
        $data_list = Activity_Model::where($map)->order($order)->paginate();

        // 分页数据
        $page = $data_list->render();

        $btn_add = [
            'title' => '新增活动',
            'icon' => 'fa fa-fw fa-plus',
            'class' => 'btn btn-info',
            'href' => url('add'),
        ];

        $btn_edit = [
            'title' => '修改活动',
            'icon' => 'fa fa-fw fa-pencil',
            'class' => 'btn btn-info btn-sm',
            'href' => url('edit',['id'=>"__id__"]),
        ];

        $btn_item = [
            'title' => '添加包含的商品或者项目',
            'icon' => 'fa fa-fw fa-scribd',
            'class' => 'btn btn-info btn-sm',
            'href' => url('addItem',['id'=>"__id__"]),
        ];

        $btn_item_list = [
            'title' => '查看包含的商品或者项目',
            'icon' => 'fa fa-fw fa-sitemap',
            'class' => 'btn btn-info btn-sm',
            'href' => url('itemLists',['id'=>"__id__"]),
        ];

        //设置页面
        return ZBuilder::make('table')
            ->addColumn('id', 'ID', 'text')
            ->addColumn('sort', '排序', 'text')
            ->addColumn('name', '组合名', 'text')
            ->addColumn('date_start', '活动开始日期', 'date')
            ->addColumn('date_end', '活动结束日期', 'date')
            ->addColumn('time_start', '活动开始时间', 'text')
            ->addColumn('time_end', '活动结束日期', 'text')
            ->addColumn('right_button', '操作', 'btn')
            ->setTableName('qt_activity')// 指定数据表名
            ->addTopButton('add', $btn_add)// 添加顶部按钮
            ->addRightButton('edit', $btn_edit)// 添加顶部按钮
            ->addRightButton('item', $btn_item)// 添加顶部按钮
            ->addRightButton('lists', $btn_item_list)// 添加顶部按钮
            ->addTopButton('delete')
            ->setPrimaryKey('id')// 设置主键名为username
            ->setPageTitle('套餐列表')
            ->setRowList($data_list)// 设置表格数据
            ->setPages($page)// 设置分页数据
            ->fetch();
    }

    /**
     * 添加活动
     * @return mixed
     * @throws \think\Exception
     */
    public function add()
    {
        //判断是否提交信息
        if ($this->request->isPost()) {
            // 表单数据
            $data = $this->request->post();

            $result = $this->validate($data, 'Activity');

            if ($result!=true)$this->error($result);

            $data['date_start'] = strtotime($data['date_start']);
            $data['date_end'] = strtotime($data['date_end']);

            $info = Activity_Model::get(['name'=>$data['name']]);

            if ($info)$this->error('活动名已经存在');

            if ($page = Activity_Model::create($data)) {

                $this->success('新增成功', 'index');
            } else {
                $this->error('新增失败');
            }
        } else {

            return ZBuilder::make('form')
                ->addFormItems([
                    ['text', 'sort','','','',['排序号:']],
                    ['text', 'name','','','',['活动名称:']],
                    ['daterange','date_start,date_end','活动日期：'],
                    ['time','time_start','活动开始时间：'],
                    ['time','time_end','活动结束时间：']
                ])
                ->setPageTitle('添加活动')
                ->fetch();
        }
    }


    /**
     * 编辑活动
     * @param null $id
     * @return mixed
     * @throws \think\Exception
     */
    public function edit($id = null)
    {
        //判断是否提交信息
        if ($this->request->isPost()) {
            // 表单数据
            $data = $this->request->post();

            // 验证
            $result = $this->validate($data, 'Activity');

            if (true !== $result) $this->error($result);

            $data['date_start'] = strtotime($data['date_start']);
            $data['date_end'] = strtotime($data['date_end']);

            if (Activity_Model::where('id',$id)->update($data)) {
                $this->success('编辑成功', 'index');
            } else {
                $this->error('编辑失败');
            }
        } else {
            $info = Activity_Model::get($id);

            $info['date_start'] = date('Y-m-d',$info['date_start']);
            $info['date_end'] = date('Y-m-d',$info['date_end']);

            return ZBuilder::make('form')
                ->addFormItems([
                    ['text', 'sort','','','',['排序号:']],
                    ['text', 'name','','','',['活动名称:']],
                    ['daterange','date_start,date_end','活动日期：'],
                    ['time','time_start','活动开始时间：'],
                    ['time','time_end','活动结束时间：']
                ])
                ->setFormData($info)
                ->setPageTitle('修改活动')
                ->fetch();
        }
    }

    /**
     * 添加活动关联的商品或者项目
     * @param null $id
     * @return mixed
     * @throws \think\Exception
     */
    public function addItem($id=null)
    {
        if ($this->request->isPost())
        {
            $data = $this->request->post();


            $item = ActivityItem::get(['activity_id'=>$data['activity_id'],'item_id'=>$data['item_type']=="goods"?$data['goods_id']:$data['project_id'],'item_type'=>$data['item_type']]);

            if ($data['item_type']=="goods")
            {
                $goods = Goods_Model::get($data['goods_id']);

                $name = $goods['name'];
            }else if ($data['item_type']=='project'){
                $project = Project_Model::get($data['project_id']);
                $name = $project['name'];
            }

            if ($item)
            {
                $item->price = $item['price'];
                $item->activity_price = $item['activity_price'];
                $item->add_block_price = $item['add_block_price'];
                $item->name = $name;
                $result = $item->save();
            }else{
                $result = ActivityItem::create([
                    'activity_id'=>$data['activity_id'],
                    'item_id'=>$data['item_type']=="goods"?$data['goods_id']:$data['project_id'],
                    'item_type'=>$data['item_type'],
                    'name'=>$name,
                    'price'=>$data['price'],
                    'activity_price'=>$data['activity_price'],
                    'add_block_price'=>$data['add_block_price'],
                    ]);
            }

            $result?$this->success('操作成功','index'):$this->error('操作失败');

        }

        $goods_list = Goods_Model::column('id,name');

        $project_list = Project_Model::column('id,name');

        return ZBuilder::make('form')
            ->addHidden('activity_id',$id)
            ->addRadio('item_type','请选择内容:','',['goods'=>'商品','project'=>'项目'])
            ->addSelect('goods_id', '请选择商品', '', $goods_list)
            ->addSelect('project_id', '请选择项目', '', $project_list)
            ->setTrigger('item_type', 'goods', 'goods_id')
            ->setTrigger('item_type', 'project', 'project_id')
            ->addText('price','原价:')
            ->addText('activity_price','活动价:')
            ->addText('add_block_price','加钟价:')
            ->setPageTitle('编辑项目')
            ->fetch();
    }

    /**
     * 包含商品列表
     * @param $id
     * @return mixed
     * @throws \think\Exception
     */
    public function itemLists($id)
    {

        $list = ActivityItem::where('activity_id',$id)->select();

        foreach ($list as $k=>$v)
        {
            $list[$k]['name'] = $v['item_type']=="goods"?$v['name'].'/商品':$v['name'].'/项目';
        }

        $btn_add_activity_viper = [
            'title' => '添加会员活动价',
            'icon' => 'fa fa-fw fa-plus',
            'class' => 'btn btn-info',
            'href' => url('addActivityViper',['id'=>"__id__"]),
        ];

        $btn_activity_viper_list = [
            'title' => '会员活动价列表',
            'icon' => 'fa fa-fw fa-align-justify',
            'class' => 'btn btn-info',
            'href' => url('activityViperLists',['id'=>"__id__"]),
        ];

        //设置页面
        return ZBuilder::make('table')
            ->addColumn('id', 'ID', 'text')
            ->addColumn('name', '商品名', 'text')
            ->addColumn('price', '原价', 'text.edit')
            ->addColumn('activity_price', '活动价', 'text.edit')
            ->addColumn('add_block_price', '活动价', 'text.edit')
            ->addColumn('right_button','操作')
            ->setTableName('qt_data_combine_goods')// 指定数据表名
            ->addRightButton('activityViper', $btn_add_activity_viper)// 添加顶部按钮
            ->addRightButton('activityViperLists', $btn_activity_viper_list)// 添加顶部按钮
            ->addTopButton('delete')
            ->setTableName('qt_data_activity_item')
            ->setPrimaryKey('id')// 设置主键名为username
            ->setPageTitle('组合下单包含商品列表')
            ->setRowList($list)// 设置表格数据
            ->fetch();
    }

    /**
     * 添加每个商品对应的会员价
     * @param $id
     * @return mixed
     * @throws \think\Exception
     */
    public function addActivityViper($id)
    {

        if ($this->request->isPost())
        {
            $data = $this->request->post();

            $result = ActivityItemViper::create($data);

            $result?$this->success('操作成功','activityViperLists'):$this->error('操作失败');
        }

        $type_list = ViperType::column('id,name');

        $info = ActivityItem::get($id);

         $build = ZBuilder::make('form')
            ->addHidden('activity_item_id',$id)
            ->addSelect('viper_card_type_id', '请选择会员类型', '', [1=>'充值',2=>'viper'])
            ->addText('viper_price','会员价:');
         if ($info['item_type']=='project')
         {
             $build = $build->addText('viper_add_block_price','会员加钟价:');
         }

         return   $build->setPageTitle('编辑项目')
            ->fetch();
    }

    /**
     * 活动包含的每个商品的会员价列表
     * @param null $id
     * @return mixed
     * @throws \think\Exception
     */
    public function activityViperLists($id=null)
    {

        $map = $this->getMap();
        // 排序
        $order = $this->getOrder();
        // 数据列表
        $data_list = ActivityItemViper::where($map)->order($order)->select();


        //设置页面
        return ZBuilder::make('table')
            ->addColumn('id', 'ID', 'text')
            ->addColumn('viper_card_type_id', '会员卡类型', 'text')
            ->addColumn('viper_price', '会员价', 'text')
            ->addColumn('viper_add_block_price', '会员加钟', 'text')
            ->setTableName('qt_data_activity_item_viper')// 指定数据表名
            ->addTopButton('delete')
            ->setPrimaryKey('id')// 设置主键名为username
            ->setPageTitle('套餐列表')
            ->setRowList($data_list)// 设置表格数据
            ->fetch();
    }

}